package com.example.mymvvmdemo.models.main.fragment.device;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadFragment;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.FragmentDeviceBinding;
import com.example.mymvvmdemo.models.main.MainViewModel;
import com.example.mymvvmdemo.models.main.fragment.device.adapter.DeviceAdapter;
import com.example.mymvvmdemo.models.main.fragment.device.entity.DeviceListEntity;
import com.example.mymvvmdemo.models.main.fragment.device.entity.DeviceShortEntity;
import com.example.mymvvmdemo.models.main.fragment.device.entity.DeviceTriggerShortcutEntity;
import com.example.mymvvmdemo.net.presenter.GetPresenter;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class DeviceFragment extends BaseLoadFragment<FragmentDeviceBinding> implements DeviceAdapter.DeviceQuickListener, IView.GetView, IView.PostBodyView {

    private MainViewModel mainViewModel;
    private GetPresenter getPresenter;
    private PostBodyPresenter postBodyPresenter;
    private DeviceAdapter deviceAdapter;

    @Override
    protected void initData() {
        getPresenter = new GetPresenter(this);
        postBodyPresenter = new PostBodyPresenter(this);
        initAdapter();
    }

    @Override
    protected void initListener() {
        binding.refreshViewShowContent.setOnRefreshListener(relayout -> {
            startLoadDevice();
        });
        binding.refreshViewShowContent.setOnLoadMoreListener(relayout -> {
            startLoadDevice();
        });
    }

    /****************************************自定义方法*******************************************/
    public void setMainViewModel(MainViewModel mainViewModel) {
        this.mainViewModel = mainViewModel;
    }

    public void startLoadDevice() {
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.deviceList, hashMap, UrlTypeConstants.deviceList);
    }


    private void deviceComplete() {
        try {
            binding.refreshViewShowContent.finishRefresh();
            binding.refreshViewShowContent.finishLoadMore();
            deviceAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            LogUtils.e("deviceComplete error:" + e.getMessage());
        }
    }

    private void initAdapter() {
        deviceAdapter = new DeviceAdapter(getContext(), mainViewModel.deviceList);
        deviceAdapter.setListener(this);
        binding.recyclerView.setAdapter(deviceAdapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    private void startLoadDeviceTriggerShortcut(DeviceListEntity.DataDTO.DevicesDTO devicesDTO, DeviceShortEntity.DataDTO.ShortcutsDTO dto) {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("device_id", devicesDTO.getDevice_id());
        hashMap.put("shortcut_id", dto.getId());

        // 创建JSON对象来确保正确的格式
        JSONObject jsonObject = new JSONObject();
        RequestBody body = null;
        try {
            jsonObject.put("params", dto.getParams().toString());
            body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
        } catch (Exception e) {
        }

        postBodyPresenter.startLoadPostBody(UrlConstants.deviceTriggerShortcut, hashMap, body, UrlTypeConstants.deviceTriggerShortcut);
    }

    /*********************************适配器点击事件*****************************************/
    @Override
    public void onQuickClick(int position, DeviceListEntity.DataDTO.DevicesDTO item, DeviceShortEntity.DataDTO.ShortcutsDTO dto) {
        startLoadDeviceTriggerShortcut(item, dto);
    }

    @Override
    public void onAddDeviceClick(int position, int type) {
        DeviceListEntity.DataDTO.DevicesDTO devicesDTO = deviceAdapter.getDataList().get(position);
        if (type == deviceAdapter.TYPE_ADD) {
            mainViewModel.startAddArticleActivity(getActivity());
        } else if (type == deviceAdapter.TYPE_DEVICE) {
            mainViewModel.startDeviceDetailActivity(getActivity(), devicesDTO);
        }
    }

    /*********************************数据请求回调*****************************************/
    @Override
    public void loadGetSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.deviceList)) {
            loadDeviceListSuccess(result, code);
        }
    }

    @Override
    public void loadGetFail(String message, String type) {
        if (type.equals(UrlTypeConstants.deviceList)) {
            loadDeviceListFail();
        }
    }

    @Override
    public void loadGetAccountError(int code) {

    }

    @Override
    public void loadGetNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.deviceTriggerShortcut)) {
            loadDeviceTriggerShortcutSuccess(result, code);
        }
    }

    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.deviceTriggerShortcut)) {
            loadDeviceTriggerShortcutFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /***********************************处理请求后数据**************************************/
    private void loadDeviceTriggerShortcutSuccess(String result, int code) {
        dismissDialog();
        try {
            DeviceTriggerShortcutEntity shortcutEntity = gson.fromJson(result, DeviceTriggerShortcutEntity.class);
            String message = shortcutEntity.getData().getMessage();
            toast(message, code == 200 ? ToastUtils.TOA_S : ToastUtils.TOA_F);
        } catch (Exception e) {
            toast(R.string.fail, ToastUtils.TOA_F);
        }

    }

    private void loadDeviceTriggerShortcutFail() {
        dismissDialog();
    }


    private void loadDeviceListSuccess(String result, int code) {
        if (code != 200) {
            loadDeviceListFail();
            return;
        }
        dismissDialog();
        DeviceListEntity deviceListEntity = gson.fromJson(result, DeviceListEntity.class);
        DeviceListEntity.DataDTO data = deviceListEntity.getData();
        if (data == null) {
            loadDeviceListFail();
            return;
        }
        List<DeviceListEntity.DataDTO.DevicesDTO> devices = data.getDevices();
        mainViewModel.deviceList.clear();
        mainViewModel.deviceList.addAll(devices);
        mainViewModel.deviceList.add(null);
        deviceAdapter.notifyDataSetChanged();
        deviceComplete();

    }

    private void loadDeviceListFail() {
        dismissDialog();
        deviceComplete();
    }


    /******************************************生命周期**********************************/
    @Override
    public void onResume() {
        super.onResume();
        startLoadDevice();
    }


}
